package com.itheima.youdianda.config;

import com.itheima.youdianda.common.BaseContext;
import com.itheima.youdianda.exception.CommonException;
import com.itheima.youdianda.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import jdk.nashorn.internal.parser.Token;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Configuration
public class TokenHandler implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("x-token");
        if (token == null){
            throw new CommonException("用户未登录");
        }

        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int verifyToken = AppJwtUtil.verifyToken(claimsBody);
        if (verifyToken == 1 || verifyToken == 2){
            throw new CommonException("用户信息已失效");
        }


        assert claimsBody != null;
        String id = claimsBody.get("id").toString();
        log.info("当前用户id：{}", id);
        BaseContext.setId(id);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        BaseContext.setId(null);
        log.info("当前用户id已销毁");
    }
}
